﻿package ua.mihaylenko.canvas.controller 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import ua.mihaylenko.canvas.gui.GUIMain;
	import ua.mihaylenko.canvas.data.DataManager;
	import flash.events.IEventDispatcher;
	import flash.events.ProgressEvent;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import ua.mihaylenko.canvas.utils.Preloader;
	import flash.net.URLRequestMethod;
	/**
	 * ...
	 * @author Mihayelnko A.L.!
	 */
	public class CanvasController 
	{
		public static var FILE_LOADED:Boolean = false;
		private var uploadURL:URLRequest;
		private var file:FileReference;
		private var urlLoader:Loader;
		private var urlCheckLoader:Loader;
		private const TEST:Boolean = !true;
		public function CanvasController() 
		{
			
			EventManager.getInstance().addEventListener(CanvasEvent.SELECT_FILE, onClickSelectFile);
			uploadURL = new URLRequest(DataManager.getInatsnce().uploadDir + DataManager.getInatsnce().uploadURL);
			uploadURL.method = URLRequestMethod.POST;
			if(TEST)fileLoaded(null);
		}
		public function onClickSelectFile(event:CanvasEvent) {
			if (file) {
				removeFileListeners(file);
			}
            file = new FileReference();
			configureFileListeners(file);
            file.browse([getImageTypeFilter()]);
			EventManager.getInstance().dispatchEvent(new CanvasEvent(CanvasEvent.ENABLED_OFF));
			
		}
		private function removeFileListeners(dispatcher:IEventDispatcher) {
            dispatcher.removeEventListener(Event.CANCEL, cancelHandler);
            dispatcher.removeEventListener(Event.COMPLETE, completeHandler);
            dispatcher.removeEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            dispatcher.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            dispatcher.removeEventListener(Event.OPEN, openHandler);
            dispatcher.removeEventListener(ProgressEvent.PROGRESS, progressUploadHandler);
            dispatcher.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            dispatcher.removeEventListener(Event.SELECT, selectHandler);
            dispatcher.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA,uploadCompleteDataHandler);
			
		}
		private function removeLoaderListeners(dispatcher:IEventDispatcher):void {
            dispatcher.removeEventListener(Event.COMPLETE, fileLoaded);
            dispatcher.removeEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            dispatcher.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorLoadHandler);
            dispatcher.removeEventListener(ProgressEvent.PROGRESS, progressLoadHandler);
            dispatcher.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
		}
		private function configureLoaderListeners(dispatcher:IEventDispatcher):void {
            dispatcher.addEventListener(Event.COMPLETE, fileLoaded);
            dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorLoadHandler);
            dispatcher.addEventListener(ProgressEvent.PROGRESS, progressLoadHandler);
            dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
		}
		private function configureFileListeners(dispatcher:IEventDispatcher):void {
            dispatcher.addEventListener(Event.CANCEL, cancelHandler);
            dispatcher.addEventListener(Event.COMPLETE, completeHandler);
            dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            dispatcher.addEventListener(Event.OPEN, openHandler);
            dispatcher.addEventListener(ProgressEvent.PROGRESS, progressUploadHandler);
            dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            dispatcher.addEventListener(Event.SELECT, selectHandler);
            dispatcher.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,uploadCompleteDataHandler);
        }

        private function getImageTypeFilter():FileFilter {
            return new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png");
        }
        private function cancelHandler(event:Event):void {
			EventManager.getInstance().dispatchEvent(new CanvasEvent(CanvasEvent.ENABLED_ON));
            trace("cancelHandler: " + event);
        }
		
        private function completeHandler(event:Event):void {
            trace("completeHandler: " + event);
        }
        private function fileLoaded(event:Event):void {
			FILE_LOADED = true;
			if (!TEST) {
				var cBitmap:Bitmap = (urlLoader.content as Bitmap);
				DataManager.getInatsnce().image = cBitmap.bitmapData;
			}else {
				var bmd:BitmapData = new Granny(500, 500);
				//var bmd:BitmapData = new barak(500, 500);
				DataManager.getInatsnce().image = bmd;
			}
				
			trace("fileLoaded: " + event);
			EventManager.getInstance().dispatchEvent(new CanvasEvent(CanvasEvent.ENABLED_ON));
        }
		
        private function uploadCompleteDataHandler(event:Event):void {
			var file:FileReference = FileReference(event.target);
			if (urlLoader) {
				removeLoaderListeners(urlLoader.contentLoaderInfo);
			}
			Preloader.getInstance().label = "Load image from server";
			Preloader.getInstance().progress = 0.0;
			urlLoader = new Loader();
			configureLoaderListeners(urlLoader.contentLoaderInfo);
			DataManager.getInatsnce().fileName = file.name;
			DataManager.getInatsnce().filePrevName = "prev_"+DataManager.getInatsnce().fileName
        	urlLoader.load(new URLRequest(DataManager.getInatsnce().uploadDir + file.name));
        
		}
		
        private function httpStatusHandler(event:HTTPStatusEvent):void {
            trace("httpStatusHandler: " + event);
        }
        
        private function ioErrorHandler(event:IOErrorEvent):void {
            trace("ioErrorHandler: " + event);
        }
        private function ioErrorLoadHandler(event:IOErrorEvent):void {
            trace("ioErrorLoadHandler: " + event);
        }
        private function openHandler(event:Event):void {
            trace("openHandler: " + event);
        }

        private function progressUploadHandler(event:ProgressEvent):void {
            Preloader.getInstance().progress = Number(event.bytesLoaded / event.bytesTotal);
        }
        private function progressLoadHandler(event:ProgressEvent):void {
			Preloader.getInstance().progress = Number(event.bytesLoaded / event.bytesTotal);
        }

        private function securityErrorHandler(event:SecurityErrorEvent):void {
            trace("securityErrorHandler: " + event);
        }

        private function selectHandler(event:Event):void {
			//urlCheckLoader = new URLLoader();
			//urlCheckLoader.addEventListener(ProgressEvent.PROGRESS, existFile);
			//urlCheckLoader.load(new URLRequest(DataManager.getInatsnce().uploadDir + file.name));

            var file:FileReference = FileReference(event.target);
			
			Preloader.getInstance().label = "Upload image to server";
			Preloader.getInstance().progress = 0.0;
            file.upload(uploadURL);
			
        }
	}
	
}